import fitz  # PyMuPDF的导入名称是fitz
import re

def pdf_to_text(pdf_path, output_txt_path=None):
    """
    将PDF文件转换为文本
    :param pdf_path: PDF文件路径
    :param output_txt_path: 输出文本文件路径（可选）
    :return: 包含所有文本的字符串
    """
    text = ""

    try:
        # 打开PDF文件
        doc = fitz.open(pdf_path)

        # 遍历每一页
        for page in doc:
            # 提取当前页文本
            text += page.get_text()

        # 如果指定了输出路径，则保存到文件
        if output_txt_path:
            with open(output_txt_path, "w", encoding="utf-8") as f:
                f.write(text)

        return text

    except Exception as e:
        print(f"处理PDF时发生错误: {str(e)}")
        return None

if __name__ == "__main__":
    input_pdf = "E:\\代码\\241204606退件检测报告.pdf"
    output_txt = "E:\\代码\\output.txt"
    result = pdf_to_text(input_pdf, output_txt)
    start_hanzi = "失效模式"
    end_hanzi = "原因分析"
    # 要提取目标汉字后面的文字数量
    # num_chars_to_extract = 25
    # pattern = re.escape(target_hanzi) + r"([\s\S]{0," + str(num_chars_to_extract) + r"})"
    # match = re.search(pattern, result)
    # if match:
        # 提取匹配的内容（目标汉字后面的指定数量的文字）
        # extracted_text = match.group(1).strip()
        # print(target_hanzi,f'{extracted_text}')
    # else:
        # print("未找到目标汉字")
    '''if result:
        print("转换成功！")
        print(f"前500字符预览：{result[:500]}...")
    '''
    start_index = result.find(start_hanzi)
    if start_index != -1:
        end_index = result.find(end_hanzi, start_index + len(start_hanzi))
        if end_index != -1:
            # 提取开始汉字和结束汉字之间的数据（不包括这两个汉字本身）
            extracted_data = result[start_index + len(start_hanzi):end_index] # 取出来的一段字符串
            # print(extracted_data)

            #number_of_lines = len(extracted_data.splitlines())
            # print(number_of_lines)
            # number_of_end_lines = number_of_lines-1 #将刚才取出来的一段字符串计算行数
            # lines = extracted_data.splitlines()
            # print(lines)
            # 初始化奇数行和偶数行的列表
            lines = [line.strip() for line in extracted_data.splitlines() if line.strip()]
            odd_lines = []
            even_lines = []
            for index, line in enumerate(lines):
                if index % 2 == 0:
                    even_lines.append(line)  # 索引从0开始，所以0, 2, 4...是偶数行
                else:
                    odd_lines.append(line)  # 1, 3, 5...是奇数行
            # 输出偶数行
            print("元件位号：")
            for line in even_lines:
                print(line)
            # 输出奇数行
            print("失效模式：")
            for line in odd_lines:
                print(line)
    #         pattern = r'[a-zA-Z0-9]'
    #         matches = re.findall(pattern, extracted_data)
    #         extracted_text = ''.join(matches) # 取出来的一串只有字母和数字的字符串
    #         pattern = r'(\d)([a-zA-Z])'
    #         # 使用 re.sub 进行替换操作
    #         modified_text = re.sub(pattern, r'\1,\2', extracted_text)
    #         print(f"元件位号：{modified_text}")
    #     else:
    #         print("未找到结束汉字")
    # else:
    #     print("未找到开始汉字")